package com.dyys.extension.mybatis;

import java.net.URL;
import java.nio.charset.StandardCharsets;

import org.springframework.context.annotation.Configuration;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class MybatisSupportConfig {

	static {
		try {
			replaceGetRowValue();
		} catch (Exception e) {
			log.error("替换DefaultResultSetHandler#getRowValue失败：" + e.getMessage());
//			e.printStackTrace();
		}
	}

	private static void replaceGetRowValue() throws Exception {
		ClassPool pool = ClassPool.getDefault();
		CtClass ctClass = pool.get("org.apache.ibatis.executor.resultset.DefaultResultSetHandler");
		CtMethod ctMethod = ctClass.getDeclaredMethod("getRowValue",
				new CtClass[] { 
						pool.get("org.apache.ibatis.executor.resultset.ResultSetWrapper"),
						pool.get("org.apache.ibatis.mapping.ResultMap"), 
						pool.get("java.lang.String") });
		
		URL url = ResourceUtils.getURL("classpath:getRowValue.txt");
		byte[] bdata = FileCopyUtils.copyToByteArray(url.openStream());    
		String body = new String(bdata, StandardCharsets.UTF_8);
		
		ctMethod.setBody(body);
		ctClass.toClass();
	}
}
